package com.blb.day20231107login.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blb.day20231107login.entity.Permission;
import com.blb.day20231107login.entity.Role;
import com.blb.day20231107login.entity.User;
import com.blb.day20231107login.mapper.UserMapper;
import com.blb.day20231107login.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenheng
 * @since 2023-11-06
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<GrantedAuthority> getAuthoritiesByUsername(String username) {
        //给用户进行授权
        StringBuilder stringBuilder = new StringBuilder();
        //遍历所有权限名称，连接到字符串中
        List<Permission> permissions = userMapper.selectPermissionsByUsername(username);
        permissions.forEach(permission -> {
            stringBuilder.append(permission.getName() + ",");
        });
        //遍历所有角色，加前缀 ROLE_
        List<Role> roles = userMapper.selectRolesByUsername(username);
        roles.forEach(role -> {
            stringBuilder.append("ROLE_" + role.getName() + ",");
        });
        //将字符串转换为权限集合
        List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(stringBuilder.toString());
        return authorities;
    }

    @Override
    public List<Permission> getPermissionsWithChildrenByUsername(String username) {
        return userMapper.selectPermissionsWithChildrenByUsername(username);
    }
}
